import 'package:flutter/material.dart';
import '../models/cart_model.dart';
import '../services/cart_service.dart';

class CartProvider with ChangeNotifier {
  final CartService _cartService;

  Cart? _cart;
  bool _isLoading = false;
  String _errorMessage = '';

  CartProvider(this._cartService);

  // Getters
  Cart? get cart => _cart;
  bool get isLoading => _isLoading;
  String get errorMessage => _errorMessage;
  int get itemCount => _cart?.items.length ?? 0;
  double get totalAmount => _cart?.total ?? 0.0;

  // 获取购物车
  Future<void> fetchCart() async {
    _isLoading = true;
    notifyListeners();

    try {
      _cart = await _cartService.getCart();
      _errorMessage = '';
    } catch (e) {
      _errorMessage = '获取购物车失败: $e';
      _cart = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 添加商品到购物车
  Future<void> addToCart(String productId, int quantity) async {
    _isLoading = true;
    notifyListeners();

    try {
      _cart = await _cartService.addToCart(productId, quantity);
      _errorMessage = '';
    } catch (e) {
      _errorMessage = '添加到购物车失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 更新购物车商品数量
  Future<void> updateCartItem(String itemId, int quantity) async {
    _isLoading = true;
    notifyListeners();

    try {
      _cart = await _cartService.updateCartItem(itemId, quantity);
      _errorMessage = '';
    } catch (e) {
      _errorMessage = '更新购物车失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 从购物车移除商品
  Future<void> removeCartItem(String itemId) async {
    _isLoading = true;
    notifyListeners();

    try {
      await _cartService.removeCartItem(itemId);
      await fetchCart(); // 重新获取购物车数据
      _errorMessage = '';
    } catch (e) {
      _errorMessage = '移除商品失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 清空购物车
  Future<void> clearCart() async {
    _isLoading = true;
    notifyListeners();

    try {
      // 假设CartService有clearCart方法
      // await _cartService.clearCart();
      _cart = null;
      _errorMessage = '';
    } catch (e) {
      _errorMessage = '清空购物车失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}
